from typing import List
from collections import defaultdict
from collections import deque
from itertools import chain
import heapq

class Twitter:
    def __init__(self):
        self.tweets = defaultdict(deque)
        self.followees = defaultdict(set)
        self.time = 0
        self.tweet_time = {}

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweet_time[tweetId] = self.time
        self.time -= 1
        self.tweets[userId].appendleft(tweetId)

    def getNewsFeed(self, userId: int) -> List[int]:
        result = []
        q = []

        for followee in chain([userId], self.followees[userId]):
            if self.tweets[followee]:
                i = 0
                tweet = self.tweets[followee][i]
                heapq.heappush(q, [self.tweet_time[tweet], 0, followee, tweet])

        while q and len(result) < 10:
            time, i, followee, tweet = heapq.heappop(q)
            result.append(tweet)
            if i < len(self.tweets[followee]) - 1:
                tweet = self.tweets[followee][i+1]
                heapq.heappush(q, [self.tweet_time[tweet], i+1, followee, tweet])
        return result

    def follow(self, followerId: int, followeeId: int) -> None:
        self.followees[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        if followeeId in self.followees[followerId]:
            self.followees[followerId].remove(followeeId)

functions = ["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
args = [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]

obj = Twitter()
for func, arg in zip(functions[1:], args[1:]):
    res = eval('obj.%s(*%s)'%(func, arg))
    print(func, arg, res)

# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)